package com.xxadmin.usercenter.config.security;

import com.xxadmin.usercenter.config.security.handler.CustomAccessDeniedHandler;
import com.xxadmin.usercenter.config.security.handler.CustomAuthExceptionEntryPoint;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;

import javax.servlet.http.HttpServletResponse;

/**
 * 资源定义
 *
 * @author:chenming
 * @date:2018/9/6
 */
@Configuration
@EnableResourceServer
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http
                // 由于使用的是JWT，我们这里不需要csrf
                .csrf().disable()
                // 基于token，所以不需要session
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                .requestMatchers().anyRequest()
                .and()
                .authorizeRequests()
                // 获取权限的要公开
                .antMatchers("/oauth/*").permitAll()
                // 除了获取权限外，其余的都要鉴权认证
                .anyRequest().authenticated()
                .and()
                .httpBasic()
        ;

        //添加自定义异常处理器
        http.exceptionHandling()
                // 处理  tokan 校验失败返回信
                .authenticationEntryPoint(new CustomAuthExceptionEntryPoint())

                // 用来解决认证过的用户访问无权限资源时的异常
                .accessDeniedHandler(new CustomAccessDeniedHandler());
    }

    @Override
    public void configure(ResourceServerSecurityConfigurer resource) throws Exception {
        // 配置自定义异常
        resource.authenticationEntryPoint(new CustomAuthExceptionEntryPoint())
                .accessDeniedHandler(new CustomAccessDeniedHandler());
    }
}
